package cn.sc.summer.auth.filter;

import cn.hutool.core.util.StrUtil;
import cn.sc.summer.auth.filter.base.BaseAuthenticationFilter;
import cn.sc.summer.auth.token.LoginToken;
import cn.sc.summer.token.constant.LoginAPIConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 类名：手机号+密码登录
 *
 * @author a-xin
 * @date 2023/11/23 14:06
 */
@Slf4j
public class LoginFilter extends BaseAuthenticationFilter {

    private static final long serialVersionUID = 631725906415541877L;

    public LoginFilter() {
        super(new AntPathRequestMatcher(LoginAPIConstant.LOGIN_API, DEFAULT_METHOD));
    }

    /**
     * Request a parameter validation
     *
     * @param requestParam Parameter information of the request
     */
    @Override
    public void paramCheck(HttpServletRequest request, Map<String, String> requestParam) {
        String username = requestParam.getOrDefault(USER_NAME, "");
        String password = requestParam.getOrDefault(PASSWORD, "");
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            throw new AuthenticationServiceException("The userName or passWord can not be null！");
        }
    }

    /**
     * The verification is successful, and the login authentication information is encapsulated
     *
     * @param request      Request body information
     * @param response     Response body information
     * @param requestParam Parameter information of the request
     * @return the login authentication information
     */
    @Override
    public Authentication checkSuccess(HttpServletRequest request, HttpServletResponse response, Map<String, String> requestParam) {
        String username = requestParam.getOrDefault(USER_NAME, "");
        String password = requestParam.getOrDefault(PASSWORD, "");
        LoginToken token = new LoginToken(username, password);
        token.setDetails(authenticationDetailsSource.buildDetails(request));
        token.setRequestParam(requestParam);
        return this.getAuthenticationManager().authenticate(token);
    }

    /**
     * Determine the types of data sources supported by this class
     *
     * @return Supported data source types
     */
    @Override
    public String supports() {
        return DEFAULT_METHOD;
    }

}


